<template>
  <div class="main">
    <a-form
      id="formLogin"
      class="user-layout-login"
      ref="formLogin"
      :form="form"
      @submit="handleSubmit">
      <a-alert v-if="isLoginError" type="error" showIcon style="margin-bottom: 24px;" message="账户或密码错误（admin/ant.design )" />
      <a-form-item>
        <a-input
          size="large"
          type="text"
          placeholder="请输入用户名"
          v-decorator="[
            'username',
            {rules: [{ required: true, message: '请输入帐户名' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
          ]"
        >
          <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input>
      </a-form-item>

      <a-form-item>
        <a-input
          size="large"
          type="password"
          autocomplete="false"
          placeholder="请输入密码"
          v-decorator="[
            'password',
            {rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}
          ]"
        >
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input>
      </a-form-item>
      <a-form-item class="img_code_form_item">
        <a-input
          size="large"
          type="text"
          autocomplete="false"
          placeholder="请输入图形码"
          v-decorator="[
            'imgcode',
            {rules: [{ required: true, message: '请输入图形码' }], validateTrigger: 'blur'}
          ]">
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
          <img @click="imgCodeClick" slot="addonAfter" :src="imgCode+captchaId">
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-checkbox v-decorator="['rememberMe']" :checked="checked" @change="checkboxChange">记住密码</a-checkbox>
      </a-form-item>

      <a-form-item style="margin-top:24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
        >确定</a-button>
      </a-form-item>
    </a-form>

    <two-step-captcha
      v-if="requiredTwoStepCaptcha"
      :visible="stepCaptchaVisible"
      @success="stepCaptchaSuccess"
      @cancel="stepCaptchaCancel"
    ></two-step-captcha>
  </div>
</template>

<script>
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import utils from '@/utils/common'
var timeStamp = Number(new Date())
export default {
  components: {
    TwoStepCaptcha
  },
  data () {
    return {
      checked: false,
      imgCode: '',
      captchaId: '',
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    }
  },
  created () {
    this.imgCode = this.$store.getters.imgCode
    this.captchaId = this.$store.state.ApiForm + utils.randomString(32)
  },
  mounted () {
    this.$nextTick(() => {
      if (localStorage.getItem('username')) {
        this.checked = true
        this.form.setFieldsValue({
          rememberMe: true,
          username: localStorage.getItem('username'),
          password: localStorage.getItem('password')
        })
      } else {
        this.checked = false
        this.form.setFieldsValue({
          rememberMe: false,
          username: '',
          password: ''
        })
      }
    })
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    // handler
    handleUsernameOrEmail (rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick (key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    imgCodeClick () {
      this.captchaId = this.$store.state.ApiForm + utils.randomString(32)
    },
    checkboxChange (e) {
      this.checked = e.target.checked
    },
    handleSubmit (e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        Login
      } = this

      state.loginBtn = true

      const validateFieldsKey = ['username', 'password', 'imgcode']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          console.log('login form', values)
          if (this.form.getFieldValue('rememberMe')) {
            this.form.setFieldsValue({
              username: localStorage.setItem('username', values.username),
              password: localStorage.setItem('password', values.password)
            })
          } else {
            this.form.setFieldsValue({
              username: localStorage.removeItem('username'),
              password: localStorage.removeItem('password')
            })
          }
          const loginParams = {
            token: utils.AnonToken(timeStamp),
            timestamp: timeStamp,
            loginName: values.username,
            password: values.password,
            rememberMe: this.form.getFieldValue('rememberMe'),
            captcha: values.imgcode,
            captchaId: this.captchaId
          }
          Login(loginParams)
            .then(res => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    stepCaptchaSuccess () {
      this.loginSuccess()
    },
    stepCaptchaCancel () {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    loginSuccess (res) {
      if (res.status === 200 || res.status === '200') {
        if (this.$route.query.redirect) {
          window.location.replace(this.$route.query.redirect)
        } else {
          window.location.replace('/data/index')
        }
        // 延迟 1 秒显示欢迎信息
        setTimeout(() => {
          this.$notification.success({
            message: '欢迎',
            description: `${timeFix()}，欢迎回来`
          })
        }, 1000)
        this.isLoginError = false
      } else {
        this.requestFailed(res)
      }
    },
    requestFailed (res) {
      this.captchaId = this.$store.state.ApiForm + utils.randomString(32)
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: res.message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  }
}
</script>

<style lang="less" scoped>
.user-layout-login {
  margin-top: 30px;
  label {
    font-size: 14px;
  }
  .img_code_form_item {
    img{
      width:120px;
      height: 35px;
    }
    & /deep/ .ant-input-group-addon{
      padding: 0 0;
    }
  }
  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
